package com.youyi.yyfilepickerlibrary.core.util;

import android.content.Context;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import com.youyi.yyfilepickerlibrary.core.model.BreadModel;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

public final class FileUtils {
    public static final int BY_EXTENSION_ASC = 6;
    public static final int BY_EXTENSION_DESC = 7;
    public static final int BY_NAME_ASC = 0;
    public static final int BY_NAME_DESC = 1;
    public static final int BY_SIZE_ASC = 4;
    public static final int BY_SIZE_DESC = 5;
    public static final int BY_TIME_ASC = 2;
    public static final int BY_TIME_DESC = 3;

    @Retention(RetentionPolicy.SOURCE)
    public @interface SortType {
    }

    public static String separator(String str) {
        String str2 = File.separator;
        String replace = str.replace("\\", str2);
        if (replace.endsWith(str2)) {
            return replace;
        }
        return replace + str2;
    }

    public static List<BreadModel> getBreadModeListFromPath(List<String> list, String str) {
        List<String> arrayList = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            if (i == 0) {
                str = str.replace(list.get(i), "/内部存储设备");
            } else {
                str = str.replace(list.get(i), "/SD卡" + i);
            }
        }
        if (!TextUtils.isEmpty(str)) {
            arrayList = Arrays.asList(str.substring(1, str.length()).split("/"));
        }
        ArrayList arrayList2 = new ArrayList();
        for (String str2 : arrayList) {
            BreadModel breadModel = new BreadModel();
            breadModel.setCurName(str2);
            arrayList2.add(breadModel);
        }
        return arrayList2;
    }

    public static String getBreadModelListByPosition(List<String> list, List<BreadModel> list2, int i) {
        StringBuilder sb = new StringBuilder("/");
        int i2 = 0;
        while (i2 < list2.size() && i >= i2) {
            sb.append(list2.get(i2).getCurName());
            sb.append(File.separator);
            i2++;
        }
        String sb2 = sb.toString();
        if (sb2.startsWith("/内部存储设备")) {
            return sb2.replace("/内部存储设备", list.get(0));
        }
        if (!sb2.startsWith("/SD卡")) {
            return sb2;
        }
        return sb2.replace("/SD卡" + String.valueOf(sb2.charAt(4)), list.get(Integer.valueOf(String.valueOf(sb2.charAt(4))).intValue()));
    }

    public static String getChangeSdCard(String str, List<String> list) {
        if (TextUtils.isEmpty(str)) {
            return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
        } else if (str.startsWith("内部存储设备")) {
            return list.get(0) + File.separator;
        } else if (str.startsWith("SD卡")) {
            return list.get(Integer.valueOf(String.valueOf(str.charAt(3))).intValue()) + File.separator;
        } else {
            return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
        }
    }

    public static boolean canBackParent(String str, List<String> list) {
        Iterator<String> it = list.iterator();
        while (it.hasNext()) {
            if (str.equals(it.next() + File.separator)) {
                return false;
            }
        }
        return true;
    }

    public static void closeSilently(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException unused) {
            }
        }
    }

    public static File[] listDirs(String str, String[] strArr, int i) {
        ArrayList arrayList = new ArrayList();
        File file = new File(str);
        if (!file.isDirectory()) {
            return new File[0];
        }
        File[] listFiles = file.listFiles(new FileFilter() {
            /* class com.youyi.yyfilepickerlibrary.core.util.FileUtils.AnonymousClass1 */

            public boolean accept(File file) {
                return file != null && file.isDirectory();
            }
        });
        if (listFiles == null) {
            return new File[0];
        }
        if (strArr == null) {
            strArr = new String[0];
        }
        for (File file2 : listFiles) {
            File absoluteFile = file2.getAbsoluteFile();
            if (!ConvertUtils.toString(strArr).contains(absoluteFile.getName())) {
                arrayList.add(absoluteFile);
            }
        }
        if (i == 0) {
            Collections.sort(arrayList, new SortByName());
        } else if (i == 1) {
            Collections.sort(arrayList, new SortByName());
            Collections.reverse(arrayList);
        } else if (i == 2) {
            Collections.sort(arrayList, new SortByTime());
        } else if (i == 3) {
            Collections.sort(arrayList, new SortByTime());
            Collections.reverse(arrayList);
        } else if (i == 4) {
            Collections.sort(arrayList, new SortBySize());
        } else if (i == 5) {
            Collections.sort(arrayList, new SortBySize());
            Collections.reverse(arrayList);
        } else if (i == 6) {
            Collections.sort(arrayList, new SortByExtension());
        } else if (i == 7) {
            Collections.sort(arrayList, new SortByExtension());
            Collections.reverse(arrayList);
        }
        return (File[]) arrayList.toArray(new File[arrayList.size()]);
    }

    public static File[] listDirs(String str, String[] strArr) {
        return listDirs(str, strArr, 0);
    }

    public static File[] listDirs(String str) {
        return listDirs(str, null, 0);
    }

    public static File[] listDirsAndFiles(String str, String[] strArr) {
        File[] fileArr;
        File[] listDirs = listDirs(str);
        if (strArr == null) {
            fileArr = listFiles(str);
        } else {
            fileArr = listFiles(str, strArr);
        }
        if (listDirs == null || fileArr == null) {
            return null;
        }
        File[] fileArr2 = new File[(listDirs.length + fileArr.length)];
        System.arraycopy(listDirs, 0, fileArr2, 0, listDirs.length);
        System.arraycopy(fileArr, 0, fileArr2, listDirs.length, fileArr.length);
        return fileArr2;
    }

    public static File[] listDirsAndFiles(String str) {
        return listDirsAndFiles(str, null);
    }

    public static File[] listFiles(String str, final Pattern pattern, int i) {
        LogUtils.verbose(String.format("list file %s", str));
        ArrayList arrayList = new ArrayList();
        File file = new File(str);
        if (!file.isDirectory()) {
            return new File[0];
        }
        File[] listFiles = file.listFiles(new FileFilter() {
            /* class com.youyi.yyfilepickerlibrary.core.util.FileUtils.AnonymousClass2 */

            public boolean accept(File file) {
                if (file == null || file.isDirectory()) {
                    return false;
                }
                if (pattern == null) {
                    return true;
                }
                return pattern.matcher(file.getName()).find();
            }
        });
        if (listFiles == null) {
            return new File[0];
        }
        for (File file2 : listFiles) {
            arrayList.add(file2.getAbsoluteFile());
        }
        if (i == 0) {
            Collections.sort(arrayList, new SortByName());
        } else if (i == 1) {
            Collections.sort(arrayList, new SortByName());
            Collections.reverse(arrayList);
        } else if (i == 2) {
            Collections.sort(arrayList, new SortByTime());
        } else if (i == 3) {
            Collections.sort(arrayList, new SortByTime());
            Collections.reverse(arrayList);
        } else if (i == 4) {
            Collections.sort(arrayList, new SortBySize());
        } else if (i == 5) {
            Collections.sort(arrayList, new SortBySize());
            Collections.reverse(arrayList);
        } else if (i == 6) {
            Collections.sort(arrayList, new SortByExtension());
        } else if (i == 7) {
            Collections.sort(arrayList, new SortByExtension());
            Collections.reverse(arrayList);
        }
        return (File[]) arrayList.toArray(new File[arrayList.size()]);
    }

    public static File[] listFiles(String str, Pattern pattern) {
        return listFiles(str, pattern, 0);
    }

    public static File[] listFiles(String str) {
        return listFiles(str, null, 0);
    }

    public static File[] listFiles(String str, final String[] strArr) {
        LogUtils.verbose(String.format("list file %s", str));
        return new File(str).listFiles(new FilenameFilter() {
            /* class com.youyi.yyfilepickerlibrary.core.util.FileUtils.AnonymousClass3 */

            public boolean accept(File file, String str) {
                return ConvertUtils.toString(strArr).contains(FileUtils.getExtension(str));
            }
        });
    }

    public static File[] listFiles(String str, String str2) {
        return listFiles(str, new String[]{str2});
    }

    public static boolean exist(String str) {
        return new File(str).exists();
    }

    public static boolean delete(File file, boolean z) {
        boolean z2 = true;
        LogUtils.verbose(String.format("delete file %s", file.getAbsolutePath()));
        if (file.isFile()) {
            return deleteResolveEBUSY(file);
        }
        File[] listFiles = file.listFiles();
        if (listFiles == null) {
            return false;
        }
        if (listFiles.length != 0) {
            boolean z3 = false;
            for (File file2 : listFiles) {
                delete(file2, z);
                z3 = deleteResolveEBUSY(file2);
            }
            z2 = z3;
        } else if (!z || !deleteResolveEBUSY(file)) {
            z2 = false;
        }
        return z ? deleteResolveEBUSY(file) : z2;
    }

    private static boolean deleteResolveEBUSY(File file) {
        File file2 = new File(file.getAbsolutePath() + System.currentTimeMillis());
        file.renameTo(file2);
        return file2.delete();
    }

    public static boolean delete(String str, boolean z) {
        File file = new File(str);
        if (file.exists()) {
            return delete(file, z);
        }
        return false;
    }

    public static boolean delete(String str) {
        return delete(str, false);
    }

    public static boolean delete(File file) {
        return delete(file, false);
    }

    public static boolean copy(String str, String str2) {
        File file = new File(str);
        return file.exists() && copy(file, new File(str2));
    }

    public static boolean copy(File file, File file2) {
        try {
            LogUtils.verbose(String.format("copy %s to %s", file.getAbsolutePath(), file2.getAbsolutePath()));
            if (file.isFile()) {
                FileInputStream fileInputStream = new FileInputStream(file);
                FileOutputStream fileOutputStream = new FileOutputStream(file2);
                BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
                byte[] bArr = new byte[8192];
                while (true) {
                    int read = bufferedInputStream.read(bArr);
                    if (read == -1) {
                        break;
                    }
                    bufferedOutputStream.write(bArr, 0, read);
                }
                bufferedInputStream.close();
                bufferedOutputStream.close();
            } else if (file.isDirectory()) {
                File[] listFiles = file.listFiles();
                file2.mkdirs();
                for (File file3 : listFiles) {
                    copy(file3.getAbsoluteFile(), new File(file2.getAbsoluteFile(), file3.getName()));
                }
            }
            return true;
        } catch (Exception e) {
            LogUtils.error(e);
            return false;
        }
    }

    public static boolean move(String str, String str2) {
        return move(new File(str), new File(str2));
    }

    public static boolean move(File file, File file2) {
        return rename(file, file2);
    }

    public static boolean rename(String str, String str2) {
        return rename(new File(str), new File(str2));
    }

    public static boolean rename(File file, File file2) {
        LogUtils.verbose(String.format("rename %s to %s", file.getAbsolutePath(), file2.getAbsolutePath()));
        return file.renameTo(file2);
    }

    public static String readText(String str, String str2) {
        LogUtils.verbose(String.format("read %s use %s", str, str2));
        try {
            byte[] readBytes = readBytes(str);
            if (readBytes != null) {
                return new String(readBytes, str2).trim();
            }
            return "";
        } catch (UnsupportedEncodingException e) {
            LogUtils.warn(e);
            return "";
        }
    }

    public static String readText(String str) {
        return readText(str, "utf-8");
    }

    public static byte[] readBytes(String str) {
        Throwable th;
        IOException e;
        FileInputStream fileInputStream;
        LogUtils.verbose(String.format("read %s", str));
        FileInputStream fileInputStream2 = null;
        try {
            fileInputStream = new FileInputStream(str);
            try {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] bArr = new byte[1024];
                while (true) {
                    int read = fileInputStream.read(bArr, 0, 1024);
                    if (read == -1) {
                        byte[] byteArray = byteArrayOutputStream.toByteArray();
                        byteArrayOutputStream.close();
                        closeSilently(fileInputStream);
                        return byteArray;
                    }
                    byteArrayOutputStream.write(bArr, 0, read);
                }
            } catch (IOException e2) {
                e = e2;
                try {
                    LogUtils.warn(e);
                    closeSilently(fileInputStream);
                    return null;
                } catch (Throwable th2) {
                    th = th2;
                    fileInputStream2 = fileInputStream;
                    closeSilently(fileInputStream2);
                    throw th;
                }
            }
        } catch (IOException e3) {
            e = e3;
            fileInputStream = null;
            LogUtils.warn(e);
            closeSilently(fileInputStream);
            return null;
        } catch (Throwable th3) {
            th = th3;
            closeSilently(fileInputStream2);
        }
        return null;
    }

    public static boolean writeText(String str, String str2, String str3) {
        try {
            writeBytes(str, str2.getBytes(str3));
            return true;
        } catch (UnsupportedEncodingException e) {
            LogUtils.warn(e);
            return false;
        }
    }

    public static boolean writeText(String str, String str2) {
        return writeText(str, str2, "utf-8");
    }

    public static boolean writeBytes(String str, byte[] bArr) {
        Throwable th;
        IOException e;
        LogUtils.verbose(String.format("write %s", str));
        File file = new File(str);
        FileOutputStream fileOutputStream = null;
        try {
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            FileOutputStream fileOutputStream2 = new FileOutputStream(str);
            try {
                fileOutputStream2.write(bArr);
                closeSilently(fileOutputStream2);
                return true;
            } catch (IOException e2) {
                e = e2;
                fileOutputStream = fileOutputStream2;
                try {
                    LogUtils.warn(e);
                    closeSilently(fileOutputStream);
                    return false;
                } catch (Throwable th2) {
                    th = th2;
                    closeSilently(fileOutputStream);
                }
            } catch (Throwable th3) {
                th = th3;
                fileOutputStream = fileOutputStream2;
                closeSilently(fileOutputStream);
            }
        } catch (IOException e3) {
            e = e3;
            LogUtils.warn(e);
            closeSilently(fileOutputStream);
            return false;
        }
        return false;
    }

    public static boolean appendText(String str, String str2) {
        Throwable th;
        IOException e;
        LogUtils.verbose(String.format("append %s", str));
        File file = new File(str);
        FileWriter fileWriter = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fileWriter2 = new FileWriter(file, true);
            try {
                fileWriter2.write(str2);
                closeSilently(fileWriter2);
                return true;
            } catch (IOException e2) {
                e = e2;
                fileWriter = fileWriter2;
                try {
                    LogUtils.warn(e);
                    closeSilently(fileWriter);
                    return false;
                } catch (Throwable th2) {
                    th = th2;
                    closeSilently(fileWriter);
                }
            } catch (Throwable th3) {
                th = th3;
                fileWriter = fileWriter2;
                closeSilently(fileWriter);
            }
        } catch (IOException e3) {
            e = e3;
            LogUtils.warn(e);
            closeSilently(fileWriter);
            return false;
        }
        return false;
    }

    public static long getLength(String str) {
        File file = new File(str);
        if (!file.isFile() || !file.exists()) {
            return 0;
        }
        return file.length();
    }

    public static String getName(String str) {
        if (str == null) {
            return "";
        }
        int lastIndexOf = str.lastIndexOf(47);
        if (lastIndexOf >= 0) {
            return str.substring(lastIndexOf + 1);
        }
        return String.valueOf(System.currentTimeMillis()) + "." + getExtension(str);
    }

    public static String getNameExcludeExtension(String str) {
        try {
            String name = new File(str).getName();
            int lastIndexOf = name.lastIndexOf(".");
            return lastIndexOf != -1 ? name.substring(0, lastIndexOf) : name;
        } catch (Exception e) {
            LogUtils.warn(e);
            return "";
        }
    }

    public static String getSize(String str) {
        return ConvertUtils.toFileSizeString(getLength(str));
    }

    public static String getExtension(String str) {
        int lastIndexOf = str.lastIndexOf(46);
        return lastIndexOf >= 0 ? str.substring(lastIndexOf + 1) : "ext";
    }

    public static String getMimeType(String str) {
        String extension = getExtension(str);
        MimeTypeMap singleton = MimeTypeMap.getSingleton();
        return singleton.hasExtension(extension) ? singleton.getMimeTypeFromExtension(extension) : "*/*";
    }

    public static String getDateTime(String str) {
        return getDateTime(str, "yyyy-MM-dd HH:mm");
    }

    public static String getDateTime(String str, String str2) {
        return getDateTime(new File(str), str2);
    }

    public static String getDateTime(File file, String str) {
        Calendar instance = Calendar.getInstance();
        instance.setTimeInMillis(file.lastModified());
        return DateUtils.formatDate(instance.getTime(), str);
    }

    public static int compareLastModified(String str, String str2) {
        int i = (new File(str).lastModified() > new File(str2).lastModified() ? 1 : (new File(str).lastModified() == new File(str2).lastModified() ? 0 : -1));
        if (i > 0) {
            return 1;
        }
        return i < 0 ? -1 : 0;
    }

    public static boolean makeDirs(String str) {
        return makeDirs(new File(str));
    }

    public static boolean makeDirs(File file) {
        return file.mkdirs();
    }

    public static class SortByExtension implements Comparator<File> {
        public int compare(File file, File file2) {
            if (file == null || file2 == null) {
                return file == null ? -1 : 1;
            }
            if (file.isDirectory() && file2.isFile()) {
                return -1;
            }
            if (!file.isFile() || !file2.isDirectory()) {
                return file.getName().compareToIgnoreCase(file2.getName());
            }
            return 1;
        }
    }

    public static class SortByName implements Comparator<File> {
        private boolean caseSensitive;

        public SortByName(boolean z) {
            this.caseSensitive = z;
        }

        public SortByName() {
            this.caseSensitive = false;
        }

        public int compare(File file, File file2) {
            if (file == null || file2 == null) {
                return file == null ? -1 : 1;
            }
            if (file.isDirectory() && file2.isFile()) {
                return -1;
            }
            if (file.isFile() && file2.isDirectory()) {
                return 1;
            }
            String name = file.getName();
            String name2 = file2.getName();
            if (this.caseSensitive) {
                return name.compareTo(name2);
            }
            return name.compareToIgnoreCase(name2);
        }
    }

    public static class SortBySize implements Comparator<File> {
        public int compare(File file, File file2) {
            if (file == null || file2 == null) {
                return file == null ? -1 : 1;
            }
            if (!file.isDirectory() || !file2.isFile()) {
                return ((!file.isFile() || !file2.isDirectory()) && file.length() < file2.length()) ? -1 : 1;
            }
            return -1;
        }
    }

    public static class SortByTime implements Comparator<File> {
        public int compare(File file, File file2) {
            if (file == null || file2 == null) {
                return file == null ? -1 : 1;
            }
            if (!file.isDirectory() || !file2.isFile()) {
                return ((!file.isFile() || !file2.isDirectory()) && file.lastModified() > file2.lastModified()) ? -1 : 1;
            }
            return -1;
        }
    }

    public static List<String> getAllSdPaths(Context context) {
        String[] strArr;
        StorageManager storageManager = (StorageManager) context.getSystemService("storage");
        try {
            strArr = (String[]) storageManager.getClass().getMethod("getVolumePaths", new Class[0]).invoke(storageManager, new Object[0]);
        } catch (Exception e) {
            e.printStackTrace();
            strArr = null;
        }
        if (strArr != null) {
            return Arrays.asList(strArr);
        }
        return new ArrayList();
    }

    public static List<String> getAllSdCardList(List<String> list) {
        ArrayList arrayList = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            if (i == 0) {
                arrayList.add("内部存储设备");
            } else {
                arrayList.add("SD卡" + i);
            }
        }
        return arrayList;
    }
}
